<?php
// +----------------------------------------------------------------------
// | INPHP
// | Copyright (c) https://inphp.cc All rights reserved.
// | 该文件源码由INPHP官方提供，使用协议以INPHP官方公告为准。
// +----------------------------------------------------------------------
// | 
// +----------------------------------------------------------------------
namespace app\vits\http\api;

use Inphp\Core\Config;
use Inphp\Core\Modules;
use Inphp\Core\Object\Message;
use Inphp\Core\Util\Str;

class data
{
    public function list(): array
    {
        $type = GET("type");
        $type = $type == "gpt" || $type == "so" ? $type : null;
        return $this->getList($type);
    }

    private function getList(?string $type = null)
    {
        $list = [];
        if (is_null($type)) {
            $list = array_merge($this->getList("gpt"), $this->getList("so"));
        }
        $tmp = [];
        $dir = Modules::getModule("vits")->getConfig($type);
        if (is_string($dir) && is_dir($dir)) {
            if ($res = opendir($dir)) {
                while ($fileName = readdir($res)) {
                    if(stripos($fileName, ".") !== 0) {
                        //过滤
                        $suffix = strtolower(strrchr($fileName, "."));
                        if ($suffix == ".pth" || $suffix == ".ckpt") {
                            $key = substr($fileName, 0, -strlen($suffix));
                        } else {
                            $key = stripos($fileName, "_audio{$suffix}") > 0 ? substr($fileName, 0, -strlen("_audio{$suffix}")) : (stripos($fileName, "_txt{$suffix}") > 0 ? substr($fileName, 0, -strlen("_txt{$suffix}")) : '');
                        }
                        if (empty($key)) continue;
                        $encoding = mb_detect_encoding($key, ['GBK', 'UTF-8', 'ASCII'], true);
                        if ($encoding === "GBK") {
                            //转换
                            $key =  iconv('GBK', 'UTF-8//IGNORE', $key);
                        }
                        $hash = md5($key);
                        if (!isset($tmp[$hash])) {
                            $tmp[$hash] = [
                                "encoding"  => $encoding,
                                "hash"      => $hash,
                                "name"      => $key,
                                "type"      => $type,
                                "suffix"    => substr($suffix, 1),
                                "model"     => $dir.$key.$suffix
                            ];
                        }
                        if ($suffix == ".mp3" || $suffix == ".wav") {
                            $tmp[$hash]["audio"] = $dir."/".$fileName;
                        }
                        if ($suffix == ".txt") {
                            $tmp[$hash]["audioText"] = file_get_contents($dir."/".$fileName);
                        }
                    }
                }
                closedir($res);
            }
        }
        foreach ($tmp as $t) {
            $list[] = $t;
        }
        return $list;
    }

    public function getTags(?string $key = null): array
    {
        //标签是保存到本地的
        $cacheDir = Config::get("define.cache")."/vits";
        if (!is_dir($cacheDir)) {
            @mkdir($cacheDir, 0777, true);
        }
        //
        $file = $cacheDir."/tags.json";
        if (!is_file($file)) {
            return [];
        }
        $tags = @file_get_contents($file);
        $tags = !empty($tags) ? (@json_decode($tags, true)) : [];
        if (!empty($key)) {
            return $tags[$key] ?? [];
        }
        return $tags;
    }

    public function setTag(): Message
    {
        $type = POST("type");
        $type = $type != "gpt" && $type != "so" ? "" : $type;
        if (empty($type)) {
            return httpMessage('类型无效');
        }
        $name = POST("name");
        $name = !empty($name) ? $name : null;
        if (empty($name)) {
            return httpMessage('名称无效');
        }
        $values = POST("values");
        $values = explode(" ", $values);

        $dir = Modules::getModule("vits")->getConfig($type);
        if (!is_string($dir) || !is_dir($dir)) {
            return httpMessage("未找到相关配置");
        }
        if (!is_file($dir."/{$name}.".($type == "gpt" ? "ckpt" : "pth"))) {
            return httpMessage("未找到相关文件");
        }
        //
        $tags = $this->getTags();
        $hash = md5($name);
        $tagList = [];
        foreach ($values as $val) {
            if (!in_array($val, $tagList)) {
                $tagList[] = $val;
            }
        }
        foreach ($tagList as $value) {
            if ($value == '男' && in_array('女', $tagList)) {
                array_splice($tagList, array_search('女', $tagList), 1);
            }
            if ($value == '成人' && in_array('儿童', $tagList)) {
                array_splice($tagList, array_search('儿童', $tagList), 1);
            }
            if ($value == '儿童' && in_array('成人', $tagList)) {
                array_splice($tagList, array_search('成人', $tagList), 1);
            }
            if ($value == '女' && in_array('男', $tagList)) {
                array_splice($tagList, array_search('女', $tagList), 1);
            }
            if (!in_array($value, $tagList)) {
                $tagList[] = $value;
            }
        }
        $tags[$hash] = $tagList;
        $cacheDir = Config::get("define.cache")."/vits";
        if (!is_dir($cacheDir)) {
            @mkdir($cacheDir, 0777, true);
        }
        //
        $file = $cacheDir."/tags.json";
        file_put_contents($file, json_encode($tags, 256));
        return httpMessage(0, "保存成功");
    }

    public function audio()
    {
        $type = GET("type");
        $type = $type != "gpt" && $type != "so" ? "" : $type;
        if (empty($type)) {
            return httpMessage('文件不存在 1');
        }
        $name = GET("name");
        $name = !empty($name) ? $name : null;
        if (empty($name)) {
            return httpMessage('文件不存在 2');
        }
        $dir = Modules::getModule("vits")->getConfig($type);
        if (!is_string($dir) || !is_dir($dir)) {
            return httpMessage(404);
        }
        $suffix = GET("suffix");
        $suffix = $suffix == "mp3" || $suffix == 'wav' ? $suffix : 'wav';
        // 指定WAV文件路径
        $wavFilePath = $dir."/{$name}_audio.".$suffix;

        // 检查文件是否存在
        if (!file_exists($wavFilePath)) {
            return httpMessage('文件不存在 3');
        }

        // 获取文件信息
        $fileSize = filesize($wavFilePath);
        $fileName = basename($wavFilePath);

        // 设置HTTP响应头，告诉浏览器这是一个WAV音频文件
        /*
        header("Content-Type: audio/wav");
        header("Content-Length: " . $fileSize);
        header("Content-Disposition: inline; filename=\"" . $fileName . "\"");
        header("Cache-Control: public");
        header("Pragma: public");*/
        $res = getHttpResponse();
        $res->withHeader("Content-Length", $fileSize);
        $res->withHeader("Content-Type", "audio/wav");
        $res->withHeader("Content-Disposition", "inline");
        $res->withHeader("filename", $fileName);
        $res->withHeader("Cache-Control", "public");
        $res->withHeader("Pragma", "public");
        $res->withBody(readfile($wavFilePath));
        $res->end();
    }
}